<?php

namespace app\common;

/**
 * JSON返回结构类
 *
 * @author yyzh
 *        
 */
class RenderJson {
	protected $result = [ ];
	/**
	 * JSON返回结构类
	 *
	 * @param string $data 数据
	 * @param string $success 返回状态
	 * @param string $msg 响应消息
	 *       
	 */
	public function __construct($data = false, $success = false, $message = '请求失败') {
	    $this->result ['success'] = $success;
	    $this->result ['message'] = $message;
		if ($data) {
		    $this->result ['data'] = $data;
		}
	}
	
	public function __set($name, $value) {
		$this->result [$name] = $value;
	}
	public function __get($name) {
		return $this->$this->data [$name];
	}
	public function __isset($name) {
		if (array_key_exists ( $name, $this->result )) {
			return true;
		} elseif ($this->__get ( $name )) {
			return true;
		} else {
			return false;
		}
	}
	public function __unset($name) {
		unset ( $this->result [$name] );
	}
	public function __toString() {
		return $this->toJson ();
	}
	public function setData($value, $message = '获取成功') {
	    if ($value) {
	        $this->result ['data'] = $value;
			$this->result ['success'] = true;
			$this->result ['message'] = $message;
		}
	}
	/**
	 * 获取数据数组
	 */
	public function toArray() {
		return $this->result;
	}
	/**
	 * 设置请求状态
	 *
	 * @param string $success
	 */
	public function success($success = false, $msg = '') {
		$this->result ['success'] = $success;
		$this->result ['message'] = $message;
	}
	/**
	 * 设置响应消息
	 *
	 * @param string $msg
	 */
	public function msg($msg = '请求失败') {
	    $this->result ['message'] = $message;
	}
	/**
	 * 设置返回数据
	 *
	 * @param string $data
	 */
	public function data($data = false) {
		if ($data) {
			$this->result ['data'] = $data;
		}
	}
	/**
	 * 转为JSON字符串
	 *
	 * @param string $options
	 */
	public function toJson($options = JSON_UNESCAPED_UNICODE) {
		header ( 'Content-Type:application/json' );
		
		return json_encode ( $this->toArray (), $options );
	}
}